package com.ruike.alisurface.ui.mainPage;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ruike.alisurface.R;
import com.ruike.alisurface.Serials.MsgEventBus;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.utils.BackMainUtils;
import com.voodoo.lib_utils.L;

import butterknife.BindView;

import static com.ruike.alisurface.utils.ShareKey.Type_Chshopzl;
import static com.ruike.alisurface.utils.ShareKey.Type_Chshopzl_OLD;

public class WebViewActivity extends BaseAty {
    private static String defultUrl = "https://rk.shouhuojiyun.com/activity/ic2.html?order_id=";
    //    https://www.baidu.com  http://www.jq22.com/jquery-info11529
    @BindView(R.id.web_linlayout)
    LinearLayout mLayout;

    @BindView(R.id.countDown_tv)
    TextView countDown_tv;
    WebView webViewShowWebv;
    private String Orderid;

    @Override
    protected boolean getCanToOtherApp() {
        return true;
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_web_view;
    }

    @Override
    protected void initViews() {

        //创建一个LayoutParams宽高设定为全屏
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        //创建WebView
        webViewShowWebv = new WebView(getApplicationContext());
        //设置WebView的宽高
        webViewShowWebv.setLayoutParams(layoutParams);
        //把webView添加到容器中
        mLayout.addView(webViewShowWebv);


        WebSettings webSettings = webViewShowWebv.getSettings();
        webSettings.setJavaScriptEnabled(true); // JS支持
        webSettings.setAllowContentAccess(true); // 允许访问内容
        webSettings.setAppCacheEnabled(false); // 允许缓存
        webSettings.setBuiltInZoomControls(false); // 支持缩放
        webSettings.setUseWideViewPort(true); // 使用宽视图窗口
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小

        webViewShowWebv.addJavascriptInterface(new H5WebViewJsInterface(), "android"); // 原生的WebView主要是进行产品展示
        webViewShowWebv.getSettings().setDomStorageEnabled(true); // 开启DOM缓存
        webViewShowWebv.getSettings().setDatabaseEnabled(true); // 开启（LocalStorage）数据存储
        webViewShowWebv.getSettings().setDatabasePath(this.getCacheDir().getAbsolutePath()); // 设置数据缓存路径
        // 覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开
        webViewShowWebv.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                WebView.HitTestResult hit = view.getHitTestResult();
                //hit.getExtra()为null或者hit.getType() == 0都表示即将加载的URL会发生重定向，需要做拦截处理
                if (TextUtils.isEmpty(hit.getExtra()) || hit.getType() == 0) {
                    //通过判断开头协议就可解决大部分重定向问题了，有另外的需求可以在此判断下操作
                    L.i("重定向", "重定向: " + hit.getType() + " && EXTRA（）" + hit.getExtra() + "------");
                    L.i("重定向", "GetURL: " + view.getUrl() + "\n" + "getOriginalUrl()" + view.getOriginalUrl());
                    L.d("重定向", "URL: " + url);
                }

                if (url.startsWith("http://") || url.startsWith("https://")) { //加载的url是http/https协议地址
                    view.loadUrl(url);
                    return false; //返回false表示此url默认由系统处理,url未加载完成，会继续往下走

                } else { //加载的url是自定义协议地址
                    try {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        startActivity(intent);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return true;
                }
            }
        });
    }

    @Override
    protected void initData() {
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        Orderid = bundle.getString("orderid");
        startCountdownTimer(120, countDown_tv, MainActivity.class);
        webViewShowWebv.loadUrl(defultUrl + Orderid);
        L.i("WebViewActivity:" , defultUrl + Orderid);
    }

    class H5WebViewJsInterface {
        /**
         * 关闭界面
         */
        @JavascriptInterface
        public void CloseWebAty() {
            L.i("WebViewActivity   =CloseWebAty=");
            BackMainUtils.setActivity(WebViewActivity.this);
            finish();
        }

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();

        if (!webViewShowWebv.canGoBack()) {
            BackMainUtils.setActivity(WebViewActivity.this);
            finish();
            return;
        } else {
            webViewShowWebv.goBack();
            return;
        }
    }

    @Override
    public void doEventBusResult(MsgEventBus event) {
        if (event.getType().equals(Type_Chshopzl)) {
            BackMainUtils.setActivity(WebViewActivity.this);
            finish();

            return;
        }

        if (event.getType().equals(Type_Chshopzl_OLD)) {
            BackMainUtils.setActivity(WebViewActivity.this);
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        L.i("webviewaty   =onDestroy=");
        if (webViewShowWebv != null) {
            //加载null内容
            webViewShowWebv.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            //清除历史记录
            webViewShowWebv.clearHistory();
            //移除WebView
            ((ViewGroup) webViewShowWebv.getParent()).removeView(webViewShowWebv);
            //销毁VebView
            webViewShowWebv.destroy();
            //WebView置为null
            webViewShowWebv = null;
        }
        super.onDestroy();
    }
}
